[模板]网络最大流(Dinic)

2019-07-14
模板

题意

求网络最大流

题解

Dinic

调试记录

Max要减去flow,不然反例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <cstdio>
#include <queue>
#include <cstring>
const int INF = 0x3f3f3f3f;
const int maxn = 1e5 + 5;
using namespace std;
struct E{
int to, nxt, f;
}e[maxn << 1];
int head[maxn], tot = 1;
void addedge(int u, int v, int f){
e[++tot].to = v, e[tot].nxt = head[u], e[tot].f = f;
head[u] = tot;
}
void ins(int u, int v, int f){
addedge(u, v, f);
addedge(v, u, 0);
}
int dep[maxn], now[maxn]; int n, m, S, T;
bool bfs(){
queue <int> q; while (!q.empty()) q.pop();
memset(dep, 0, sizeof dep); dep[S] = 1; q.push(S);
memcpy(now, head, sizeof now);
while (!q.empty()){
int cur = q.front(); q.pop();
for (int i = head[cur]; i; i = e[i].nxt){
if (!dep[e[i].to] && e[i].f){
q.push(e[i].to);
dep[e[i].to] = dep[cur] + 1;
}
}
}
return dep[T];
}
int dfs(int cur, int Max){
if (cur == T) return Max;
int flow = 0;
for (int i = now[cur]; i; i = e[i].nxt){
now[cur] = i;
if (flow == Max) return flow;
if (dep[e[i].to] == dep[cur] + 1 && e[i].f){
int tmp = dfs(e[i].to, min(Max - flow, e[i].f));
e[i].f -= tmp;
e[i ^ 1].f += tmp;
flow += tmp;
}
}
return flow;
}
int maxflow = 0;
void Dinic(){
while (bfs())
maxflow += dfs(S, INF);
}
int main(){
scanf("%d%d%d%d", &n, &m, &S, &T);
for (int u, v, f, i = 1; i <= m; i++){
scanf("%d%d%d", &u, &v, &f);
ins(u, v, f);
}
Dinic();
printf("%d\n", maxflow);
return 0;
}